package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.DepartmentDTO;
import com.example.hello.entity.Department;
import com.example.hello.service.DepartmentService;
import com.example.hello.vo.DepartmentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/departments")
@RequiredArgsConstructor
public class DepartmentController {
    
    private final DepartmentService departmentService;

    @GetMapping
    public Result<List<DepartmentVO>> listAll() {
        List<DepartmentVO> result = departmentService.listAll().stream()
            .map(DepartmentVO::from)
            .collect(Collectors.toList());
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<DepartmentVO> getById(@PathVariable Integer id) {
        Department dept = departmentService.getById(id);
        if (dept == null) {
            return Result.error("部门不存在");
        }
        return Result.success(DepartmentVO.from(dept));
    }

    @PostMapping
    public Result<?> add(@RequestBody DepartmentDTO dto) {
        if (dto.getName() == null || dto.getName().length() < 3 || dto.getName().length() > 10) {
            return Result.error("部门名称长度需为3-10个字符");
        }
        try {
            departmentService.add(dto.getName());
            return Result.success("新增成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Integer id, @RequestBody DepartmentDTO dto) {
        if (dto.getName() == null || dto.getName().length() < 3 || dto.getName().length() > 10) {
            return Result.error("部门名称长度需为3-10个字符");
        }
        try {
            departmentService.update(id, dto.getName());
            return Result.success("修改成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        try {
            departmentService.delete(id);
            return Result.success("删除成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/{id}/approval")
    public Result<?> approve(@PathVariable Integer id) {
        boolean approved = departmentService.approve(id);
        if (!approved) {
            return Result.error("部门名称长度需为3-10个字符");
        }
        return Result.success("审核成功");
    }
}